package com.mcf.xiaolinju.controller;

import com.mcf.xiaolinju.service.impl.UserDetailsServiceImpl;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/xiaolinju")
public class PictureController {
    @Resource
    UserDetailsServiceImpl userDetailsService;

    @RequestMapping("/uploadpicture")
    //图片上传 ,int userid
    public String uploadpicture(MultipartFile file)  {
        System.out.println("进入");
        System.out.println(file.getOriginalFilename());
        if(file ==null){
            return  "图片为空，请重新上传";
        }
        String end= Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String suffix=end.toLowerCase();
        if(!suffix.equals(".png") && !suffix.equals(".jpg") && !suffix.equals(".jpeg")){
            return  "文件的格式不正确，请重新选择";
        }
        //产生一个不重复的uuid与文件名进行拼接
        String fileName= UUID.randomUUID().toString() +file.getOriginalFilename();
        //定义图片上传的路径
        String uploadPath= System.getProperty("user.dir")+"/image/";
        File filepath=new File(uploadPath);
        if(!filepath.exists()){
            filepath.mkdir();
        }
        try {
            file.transferTo(new File(uploadPath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return "文件保存异常";
        }
        String fileurl="http://localhost:8083"+"/image/"+fileName;
        System.out.println(fileurl);
        //return userDetailsService.updateportrait(fileurl,userid);
        return fileurl;
    }
}
